package xyz.zcq.zcqrpc.easy.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import xyz.zcq.zcqrpc.easy.model.RpcRequest;
import xyz.zcq.zcqrpc.easy.model.RpcResponse;
import xyz.zcq.zcqrpc.easy.serializer.JdkSerializer;
import xyz.zcq.zcqrpc.easy.serializer.Serializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理（JDK动态代理）
 */
public class ServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 获取序列化器
        Serializer serializer = new JdkSerializer();
        // 构造RPC请求对象RpcRequest
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .parameters(args)
                .build();
        // 发送请求
        try {
            byte[] reqBody = serializer.serialize(rpcRequest);
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080").body(reqBody).execute()) {
                RpcResponse rpcResponse = serializer.deserialization(httpResponse.bodyBytes(), RpcResponse.class);
                return rpcResponse.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
